import { defineStore } from 'pinia';
import type { Task, TaskStorage } from '../types/task';
import { saveToStorage, loadFromStorage } from '../utils/storage';
import { v4 as uuidv4 } from 'uuid';

export const useTaskStore = defineStore('tasks', {
  state: () => ({
    tasks: [] as Task[],
    isLoading: false,
    error: null as string | null,
  }),
  
  getters: {
    hasTasks: (state) => state.tasks.length > 0,
  },
  
  actions: {
    async initialize() {
      this.isLoading = true;
      try {
        const data = loadFromStorage();
        if (data) {
          this.tasks = data.tasks;
        }
      } catch (error) {
        this.error = '加载数据失败';
        console.error('Failed to initialize tasks:', error);
      } finally {
        this.isLoading = false;
      }
    },
    
    async addTask(task: Omit<Task, 'id' | 'createTime' | 'updateTime'>) {
      const newTask: Task = {
        ...task,
        id: uuidv4(),
        createTime: new Date().toISOString(),
        updateTime: new Date().toISOString(),
      };
      this.tasks.push(newTask);
      await this.saveTasks();
    },
    
    async updateTask(taskId: string, updates: Partial<Task>) {
      const taskIndex = this.tasks.findIndex(t => t.id === taskId);
      if (taskIndex !== -1) {
        this.tasks[taskIndex] = {
          ...this.tasks[taskIndex],
          ...updates,
          updateTime: new Date().toISOString(),
        };
        await this.saveTasks();
      }
    },
    
    async deleteTask(taskId: string) {
      this.tasks = this.tasks.filter(t => t.id !== taskId);
      await this.saveTasks();
    },
    
    async saveTasks() {
      try {
        const data: TaskStorage = {
          tasks: this.tasks,
          version: '1.0',
        };
        saveToStorage(data);
      } catch (error) {
        this.error = '保存数据失败';
        console.error('Failed to save tasks:', error);
      }
    },
    
    exportTasks() {
      const data: TaskStorage = {
        tasks: this.tasks,
        version: '1.0',
      };
      return data;
    },
    
    async importTasks(data: TaskStorage) {
      if (data.version === '1.0' && Array.isArray(data.tasks)) {
        this.tasks = data.tasks;
        await this.saveTasks();
      } else {
        throw new Error('Invalid data format');
      }
    },
  },
});